import { app, shell, BrowserWindow } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import global from '../utils/global'
import { initIpcMain } from '../ipc/ipcMain'
import { initIpcFollowWindow } from '../ipc/ipcFollowWindow'
import webSocket from '../utils/websocket'
import { initLog } from '../utils/log'
import globalPublic from '../utils/public'

initLog()

function createWindow(): void {
  global.mainWindow = new BrowserWindow({
    width: 300,
    height: 500,
    show: false,
    autoHideMenuBar: true,
    frame: false,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  global.mainWindow.on('ready-to-show', () => {
    global.mainWindow?.show()
  })

  global.mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    global.mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL)
  } else {
    global.mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()
  globalPublic.downloadAndUnzipInject()

  // 应用启动后主动向渲染进程发送消息
  // setTimeout(() => {
  //   global.mainWindow?.webContents.send('message-from-main', '这是主进程主动发送的消息')
  // }, 2000)

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  initIpcMain()
  initIpcFollowWindow()
  webSocket.createWebsocket()
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
